const db = require('../common/Db');
const game_config = require('../config/game_config');
const log = require('../utils/log');
const util = require('util')


class loginDb extends db{
    static getInstance(){
        if(!loginDb.instance){
            loginDb.instance = new loginDb();
            return loginDb.instance;
        }else{
            return loginDb.instance;
        }
    }

    constructor() {
        super();
        log.info('======loginDb 链接数据库=========')
        // this.connectSql(game_config.center_database);

        const config = {
            host: game_config.center_database.host,
            port: game_config.center_database.port,
            user: game_config.center_database.uname,
            password: game_config.center_database.upwd,
            database: game_config.center_database.db_name
        };
        this.myDb = new db(config);
        // this.test();
    }

    //测试使用
   async test(){
        try {
            await this.myDb.connect();
            const sql = 'select * from userinfo where userId = "web_ti6lrZGZ"';
            const rows = await this.myDb.query(sql, [1]);
            console.log("======tesr========",rows);
        } finally {
            await this.myDb.close();
        }
    }

    async getUserInfo(uid){
        var sql = "select * from userinfo where userId = \"%s\"";
        var sql_cmd = util.format(sql, uid);
        try {
            await this.myDb.connect();
            const rows = await this.myDb.query(sql_cmd, [1]);
            // console.log("======getUserInfo========",rows);
            return rows;
        } finally {
            await this.myDb.close();
        }
    }

    //插入一条数据
    async insetUserToMsql(uid, name, avator,isNewPlayer){
        let res = null;
        try{
            var sql = "insert into userinfo(`userId`, `name`, `avator`,`isNewPlayer`)values(\"%s\", \"%s\", \"%s\", \"%d\")";
            var sql_cmd = util.format(sql, uid, name, avator,isNewPlayer);
            try {
                await this.myDb.connect();
                const rows = await this.myDb.query(sql_cmd, [1]);
                return rows;
            } finally {
                await this.myDb.close();
            }
        }catch (e) {
            
        }
        return res;
    }

    async insetMrtzToMsql(uid){
        await db.connect();
        var sql = "insert into mrtzgame(`userId`)values(\"%s\")"
        var sql_cmd = util.format(sql, uid);
        let res = await db.query(sql_cmd);
        await db.close();
        return res;
    }

    async insetMrtzToMsql(uid,type){
        await db.connect();
        let key = `key__${uid}_${type}`;
        var sql = 'insert into tm_db(`keyOnly`,`uid`,`gamType`)values(\"%s\",\"%s\",\"%s\")';
        var sql_cmd = util.format(sql,key, uid,type);
        let res = await db.query(sql_cmd);
        await db.close();
        return res;
    }
}
global.loginSerMgr.loginDb = loginDb.getInstance();
module.exports = loginDb;